<template>
  <el-button type="primary" @click="add">
    添加用户
  </el-button>
  <el-button type="danger" @click="batchDel">
    批量删除
  </el-button>

  <el-table
      :data="userList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" width="60" />
    <el-table-column prop="login_act" label="账号" />
    <el-table-column property="name" label="姓名" show-overflow-tooltip />
    <el-table-column property="phone" label="手机" show-overflow-tooltip />
    <el-table-column property="email" label="邮箱" show-overflow-tooltip />
    <el-table-column property="create_time" label="创建时间" show-overflow-tooltip />
    <el-table-column label="操作" show-overflow-tooltip >
      <template #default="scope">
        <el-button type="primary" @click="view(scope.row.id)">详情</el-button>
        <el-button type="success" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>

  </el-table>

  <el-pagination
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      v-model:current-page="currentPage"
  />

  <!--新增 | 编辑用户的弹窗画面-->
  <el-dialog v-model="userDialogVisible" :title="userQuery.id > 0 ? '编辑用户' : '新增用户'" width="55%" center draggable>
    <el-form ref="userRefForm" :model="userQuery" label-width="110px" :rules="userRules">
      <el-form-item label="账号" prop="login_act">
        <el-input v-model="userQuery.login_act" />
      </el-form-item>

      <el-form-item label="密码" v-if="userQuery.id > 0"><!--编辑-->
        <el-input type="password" v-model="userQuery.login_pwd" />
      </el-form-item>

      <el-form-item label="密码" prop="loginPwd" v-else><!--新增-->
        <el-input type="password" v-model="userQuery.login_pwd" />
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="userQuery.name" />
      </el-form-item>

      <el-form-item label="手机" prop="phone">
        <el-input v-model="userQuery.phone" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userQuery.email" />
      </el-form-item>

      <el-form-item label="账号未过期" prop="account_no_expired">
        <el-select v-model="userQuery.account_no_expired" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="密码未过期" prop="credentials_no_expired">
        <el-select v-model="userQuery.credentials_no_expired" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="账号未锁定" prop="account_no_locked">
        <el-select v-model="userQuery.account_no_locked" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="账号是否启用" prop="account_enabled">
        <el-select v-model="userQuery.account_enabled" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="userDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="userSubmit">提 交</el-button>
      </span>
    </template>

  </el-dialog>

</template>

<script setup>
import {inject, onMounted, ref, watch} from "vue";
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import router from "../router/router.js";
import {messageConfirm, messageTip} from "../util/util.js";

//用户信息列表
let userList = ref([{}]);
//每页显示多少条数据
let pageSize = ref();
//数据总数
let total = ref();
//当前是第几页
let currentPage = ref();
//用户的弹窗是否弹出来，true就弹出来，false就不弹出来
let userDialogVisible = ref(false);
//添加用户中的值
let userQuery = ref({});
//指定添加用户的规则
let userRules = {
  login_act : [
    {required: true, message: '请输入登录账号', trigger: 'blur'}
  ],
  login_pwd : [
    {required: true, message: '请输入登录密码', trigger: 'blur'},
    {min: 6, max: 16, message: '登录密码长度为6-16位', trigger: 'blur'}
  ],
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
    {pattern: /^[\u4E00-\u9FA5]{1,5}$/, message: '姓名必须是中文', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号码', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '格式为 1:1 2:[3-9] 11位', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式有误', trigger: 'blur'}
  ],
  account_no_expired: [
    {required: true, message: '请选择账号是否未过期', trigger: 'blur'},
  ],
  credentials_no_expired: [
    {required: true, message: '请选择密码是否未过期', trigger: 'blur'},
  ],
  account_no_locked: [
    {required: true, message: '请选择账号是否未未锁定', trigger: 'blur'},
  ],
  account_enabled: [
    {required: true, message: '请选择账号是否可用', trigger: 'blur'},
  ]
}
//下拉选项数组
let options = [
  {label : '是', value : 1},
  {label : '否', value : 0}
]
//绑定添加用户表单，用于后续验证规则的实现
let userRefForm = ref();

//勾选用户的id列表
const idList = ref([]);

onMounted(()=>{
  getData(1);
})

//这个 watch 监视器传来的新值
watch(currentPage,(newPage)=>{
  console.log("当前页变化：",newPage);
  toPage(newPage);
})

//获取父亲方法|或变量
const reload = inject("reload");
const loadUser = inject("loadUser")

//勾选或取消勾选触发此函数 rowsData是一个数组，返回勾选好的多个行信息
function handleSelectionChange(rowsData) {
  idList.value = [];
  rowsData.forEach((data)=>{
    let id = data.id;
    idList.value.push(id);
  })
}
//获取用户信息
//进行分页查询，传入当前页数的值 current : current 是一种 k ：v 的简写方式
//但ES6 语法过后 可以直接 {current} 进行键值对映射，除非kv不相同才会用以前的方法
function getData(current){
  doGet("/api/users", {current:current}).then((resp)=>{
    console.log(resp);
    if(resp.data.code === 200){
      userList.value = resp.data.data.records;
      pageSize.value = resp.data.data.size;
      total.value = resp.data.data.total;
    }
  })
}

function toPage(newPage){
  getData(newPage);
}

//详情按钮
function view(id){
  console.log("跳转",id,"的详情页面");
  router.push("/dashboard/user/" + id);
}
//添加用户
function add(){
  userDialogVisible.value = true;
  userQuery.value = {};
}
//编辑按钮
function edit(id){
  userDialogVisible.value = true;
  getUser(id);
}
//删除按钮
function del(id){
  if(id === loadUser.value.id) {
    messageTip("不能删除自身用户", "error");
  }else{
    //做出提示
    messageConfirm("您确定要删除该用户吗").then(() => {
      doDelete("/api/user/" + id, {}).then((resp) => {
        if (resp.data.code === 200) {
          messageTip("用户删除成功", "success");
          reload();
        } else {
          messageTip("删除失败，原因：" + resp.data.msg, "error");
        }
      })
    }).catch(() => {
      messageTip("取消删除该用户", "warning");
    })
  }
}
//批量删除事件
const batchDel = () => {
  if(idList.value.length <= 0){
    //提示一下
    messageTip("请选择要删除的数据", "warning");
    return;
  }
  let ok = true;
  idList.value.forEach((data) => {
    if(loadUser.value.id === data) {
      ok = false;
      //forEach 用 return 跳出
      return;
    }
  })
  if(ok === false) {
    messageTip("存在自身用户，不能删除", "error");
  }else{
    //做出提示
    messageConfirm("您确定批量删除这些用户吗").then(() => {
      doDelete("/api/user", {ids : idList.value.join(",")}).then((resp) => {
        if (resp.data.code === 200) {
          messageTip("用户删除成功", "success");
          reload();
        } else {
          messageTip("删除失败，原因：" + resp.data.msg, "error");
        }
      })
    }).catch(() => {
      messageTip("取消批量删除用户", "warning");
    })
  }
}
//编辑用户时，先获取用户信息
const getUser = (id) => {
  doGet("/api/user/"+id,{}).then((resp)=>{
    if(resp.data.code === 200){
      userQuery.value = resp.data.data;
      userQuery.value.login_pwd = null;
    }
  })
}
//新用户 | 编辑用户 信息提交
function userSubmit(){
  let formData = new FormData();
  for(let field in userQuery.value){
    formData.append(field, userQuery.value[field]);
  }
  //实现 表单的验证规则
  userRefForm.value.validate( (isValid) => {
    if (isValid) {
      if(userQuery.value.id > 0){ //进入编辑
        doPut("/api/user", formData).then(resp => {/*新增*/
          if (resp.data.code === 200) {
            messageTip("提交成功", "success");
            reload();
          } else {
            messageTip("提交失败", "error");
          }
        })
      } else{ //进入新增
        doPost("/api/user", formData).then(resp => {/*新增*/
          if (resp.data.code === 200) {
            messageTip("提交成功", "success");
            reload();
          } else {
            messageTip("提交失败", "error");
          }
        })
      }

      userDialogVisible = false;
    }
  })
}
</script>

<style scoped>
.el-table {
  margin-top: 12px;
}
.el-pagination {
  margin-top: 12px;
}
.el-select {
  width: 100%;
}
</style>